package edu.its.dreamteam.web.pages.admin;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry.ComponentResources;
import org.apache.tapestry.annotations.Retain;
import org.apache.tapestry.beaneditor.BeanModel;
import org.apache.tapestry.ioc.annotations.Inject;
import org.apache.tapestry.services.BeanModelSource;

import edu.its.dreamteam.daf.beans.Player;
import edu.its.dreamteam.daf.dao.IClubDao;
import edu.its.dreamteam.daf.dao.IPlayerDao;
import edu.its.dreamteam.web.base.SecureBasePage;

public class PlayerGrid extends SecureBasePage{
	@Inject
	private IPlayerDao playerDao;
	@Inject
	private IClubDao clubDao;
	
	
	private List<Player> playerList;	
	private Player player;
	
	@Retain
	private BeanModel playerModel;
	@Inject
	private BeanModelSource beanModelSource;
	@Inject
	private ComponentResources resources;
	
	
	private int playerClubSize;
	
	private boolean delete;
	private List<String> deletedList;
    
       
	public Player getPlayer() {
		return player;
	}
	public void setPlayer(Player player) {
		this.player = player;
	}	
	public IPlayerDao getPlayerDao() {
		return playerDao;
	}			
	public IClubDao getClubDao() {
		return clubDao;
	}
	
	
	public int getPlayerClubSize() {
		playerClubSize = getPlayerList().size();
		return playerClubSize;
	}
	/*
	 * Delete properties
	 */
	public boolean isDelete() {
		return delete;
	}
	
	public void setDelete(boolean delete) {
		if(delete){
			getDeletedList().add(getPlayer().getIdPlayer());
		}
		this.delete = delete;
	}	
	
	public List<String> getDeletedList() {
		if(deletedList == null){
			deletedList = new ArrayList<String>();
		}
		return deletedList;
	}
	
	public List<Player> getPlayerList() {
		if(playerList == null){
			playerList = new ArrayList<Player>();
			playerList = getPlayerDao().queryForList("", "");
		}
		return playerList;
	}
		
	public void setPlayerList(List<Player> playerList) {
		this.playerList = playerList;
	}
		
	void pageLoaded(){
		playerModel = beanModelSource.create(Player.class, false, resources);
		playerModel.get("idClub").label("Club");
		playerModel.get("idPosition").label("Position");
		playerModel.add("actions", null).label("Edit");
		playerModel.reorder("actions");
	}
	
	Object onSuccessFromPlayerForm(){		
		for(String element : getDeletedList()){
			setPlayer((Player) getPlayerDao().findByPrimaryKey(element));
			getPlayerDao().delete(getPlayer());
		}		
		return PlayerGrid.class;
	}	
	
	public BeanModel getPlayerModel() {
		return playerModel;
	}	
}
